<?php
declare (strict_types = 1);
namespace app\api\controller;

use think\Request;
use think\facade\{Db, Log};
use think\Exception;
use think\exception\ValidateException;

use app\api\controller\BaseController;
use service\JsonService as Json;

use app\common\model\{User, Banner, Shop, ShopCate, Notice, Goods, GoodsCate, Img, ShopShare, FinancialRecord as Fin};
use app\common\validate\{UserValidate, ShopValidate};

class HomeController extends BaseController
{
    /** 
     * 上传图片 
     */
    public function img_up()
    {
        $data = input('');
    
        try{
            validate(ImgValidate::class)->scene('img')->check($data);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }
            
        $imgUrl = fileUp(request()->file('img'));
    
        return Json::success('上传成功', ['img_url' => $imgUrl]);
    }

    /**
	 * 轮播图列表
	 */
    public function getBannerList()
    {
        $list = Banner::getList([], 0, 0, 0, '*', 'id DESC');
        if($list === false) return Json::fail('暂无数据');
        return Json::success('ok', $list);
    }

    /**
	 * 公告列表
	 */
    public function getNoticeList()
    {
        $data = input('');
    
        try{
            validate(ShopValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }

        $where[] = ['shop_id', '=', $data['shop_id']];

        $field = 'id, title, content, create_time';
        $list = Notice::getList($where, 1, $data['page'], $data['limit'], $field, 'id DESC');

        if($list === false) return Json::fail('暂无数据');

        return Json::success('ok', $list);
    }

    /**
	 * 店铺分类列表
	 */
    public function getShopCateList()
    {
        $list = ShopCate::getList([], 0, 0, 0, '*', 'sort DESC');
        if($list === false) return Json::fail('暂无数据');
        return Json::success('ok', $list);
    }

    /**
	 * 店铺列表
	 */
    public function getShopList()
    {
        $cateId = Request()->param('shop_cate_id', 0);
        $page   = Request()->param('page', 1);
        $limit  = Request()->param('limit', 10);

        $where[] = ['cate_id', '=', $cateId];
        $where[] = ['status', '=', 1];
        
        $field = 'id, name, business_time, address, brief';
        $list = Shop::getList($where, 1, $page, $limit, $field, 'create_time DESC, id DESC');

        if($list === false) return Json::fail('暂无数据~');
        return Json::success('ok', $list);
    }

    /**
	 * 店铺详情
	 */
    public function getShopShow()
    {
        $shopId = Request()->param('shop_id', 0);

        $where[] = ['id', '=', $shopId];
        
        $field = 'id, name, business_time, address, brief, shareholder_num, bond_max, bond, shareholder_money';
        $info  = Shop::getFind($where, $field);

        if($info === false) return Json::fail('暂无数据~');

        $info['shareholder_num_now'] = ShopShare::getNum(['shop_id' => $shopId]);
        return Json::success('ok', $info);
    }

    /**
	 * 商品分类列表
	 */
    public function getGoodsCateList()
    {
        $list = GoodsCate::getList([], 0, 0, 0, '*', 'id');
        if($list === false) return Json::fail('暂无数据');
        return Json::success('ok', $list);
    }

    /**
	 * 商品列表
	 */
    public function getGoodsList()
    {
        $cateId = Request()->param('goods_cate_id', 0);
        $shopId = Request()->param('shop_id', -1);
        $page   = Request()->param('page', 1);
        $limit  = Request()->param('limit', 10);

        $where[] = ['cate_id', '=', $cateId];
        $where[] = ['is_show', '=', 1];
        if($shopId >= 0) $where[] = ['shop_id', '=', $shopId];
        
        $field = 'id, name, small_img, price';
        $list = Goods::getList($where, 1, $page, $limit, $field, 'create_time DESC, id DESC');

        if($list === false) return Json::fail('暂无数据~');
        return Json::success('ok', $list);
    }

    /**
	 * 商品详情
	 */
    public function getGoodsShow()
    {
        $goodsId = Request()->param('goods_id', 0);

        $field = 'id, name, price, price_origin, type, sku_list, brokerage_ratio, money_red, point_ratio';
        $info = Goods::getFind(['id' => $goodsId], $field);

        if($info === false) return Json::fail('商品不存在或已下架！');

        $info['sku_list'] = json_decode($info['sku_list'], true);

        /** 查询产品的轮播图 */
        $whereBannerImg = [
            'obj_type' => 1,
            'obj_cate' => 1,
            'obj_id'   => $goodsId,
        ];
        
        $imgList = Img::getList($whereBannerImg, 0);
        $imgList = $imgList ? $imgList->toArray() : [];

        /** 查询产品的详情图 */
        $whereShowImg = [
            'obj_type' => 1,
            'obj_cate' => 2,
            'obj_id'   => $goodsId,
        ];

        /** 查询产品的轮播图 */
        $imgShowList = Img::getList($whereShowImg, 0);
        $imgShowList = $imgShowList ? $imgShowList->toArray() : [];

        $info['banner_list'] = array_column($imgList, 'img');
        $info['show_list'] = array_column($imgShowList, 'img');

        return Json::success('ok', $info);
    }

    /**
     * 店铺入股
     */
    public function setShopShare()
    {
        $shopId     = Request()->param('shop_id', 0);
        $moneyShare = Request()->param('money_share', 0);
        $realName   = Request()->param('real_name', '');
        $mobile     = Request()->param('mobile', '');
        $cardNum    = Request()->param('card_num', '');
        $brief      = Request()->param('brief', '');
        
        $system = getSystemVal();

        if($shopId == 0 || $moneyShare == 0) return Json::fail('接收数据错误!');
        if(empty($realName) || empty($mobile) || empty($cardNum) || empty($brief)) return Json::fail('接收数据错误!');

        /** 是否入股 */
        $info = ShopShare::getFind(['user_id' => $this->user_id, 'shop_id' => $shopId]);
        if($info !== false)  return Json::fail('请勿重复入股');

        /** 店铺信息 */
        $shopInfo = Shop::getFind(['id' => $shopId]);
        if($shopInfo !== false)  return Json::fail('店铺不存在');

        /** 用户信息 */
        $userInfo = User::getFind(['id' => $this->user_id]);
        if($userInfo !== false || $userInfo['point'] < $moneyShare)  return Json::fail('积分余额不足！');
        if($userInfo['share_shop_id'] == 0)  return Json::fail('每人只能入股一个店铺');
        if($userInfo['star'] < $system['condition_share_star']) return Json::fail('入股星级不足！');
        if($userInfo['point'] < $system['condition_share_point']) return Json::fail('入股积分不足');

        /** 当前入股人数 */
        $shareNum = ShopShare::getNum(['shop_id' => $shopId]);
        if($shopInfo['shareholder_num'] < $shareNum + 1) return Json::fail('入股人数达到上限');

        $data = [
            'user_id'             => $this->user_id,
            'shop_id'             => $shopId,
            'money_share'         => $moneyShare,
            'point_to_bond_ratio' => $shopInfo['point_to_bond_ratio'],
            'real_name'           => $realName,
            'mobile'              => $mobile,
            'card_num'            => $cardNum,
            'brief'               => $brief,
        ];

        self::beginTrans();
        try {
            /** 入股 */
            $flag = ShopShare::add($data);
            if($flag === false) throw new Exception('入股失败，请稍后重试！');

            /** 更新用户入股店铺 */
            if(User::edit(['id' => $this->user_id, 'shop_share_id' => $flag->id]) === false) throw new Exception('更新入股店铺失败！');

            /** 店铺增加保证金 */
            if(Shop::setIncField(['id' => $shopId], 'bond', $moneyShare * $shopInfo['point_to_bond_ratio']) === false) throw new Exception('保证金增加失败，请稍后重试！');

            /** 用户扣除积分 */
            if(User::setDecField(['id' => $this->user_id], 'point', $moneyShare) === false) throw new Exception('积分扣除失败，请稍后重试！');
            if(Fin::adds($this->user_id, $flag->id, 1, 2, '入股店铺', $moneyShare) === false) throw new Exception('添加财务记录失败！');

            self::commitTrans();
        } catch (\Exception $e) {
            self::rollbackTrans();
            return Json::fail($e->getMessage());
        }

        return Json::success('入股成功');
    }
}